package com.Test;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;

/**
 * Created by Administrator on 2016/4/29.
 */
@WebFilter(filterName = "outputReplaceFilter")
public class outputReplaceFilter implements Filter {
    private Properties pp = new Properties();
    Log log = LogFactory.getLog(this.getClass());
    public void destroy() {
        pp = null;
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpCharacterResponseWrapper hcrw = new HttpCharacterResponseWrapper((HttpServletResponse) resp);
        chain.doFilter(req, hcrw);
        String output = hcrw.getCharArrayWriter().toString();
        log.info(pp.keySet().toString());
        for(Object obj:pp.keySet()){
            String key = (String) obj;
            output     = output.replace(key,pp.getProperty(key));
        }
        PrintWriter out = resp.getWriter();
        out.write(output);
        out.println("<!-- Generated at" + new java.util.Date() + "-->");
    }

    public void init(FilterConfig config) throws ServletException {
        String file     = config.getInitParameter("refile");
        String realpath = config.getServletContext().getRealPath(file);
        try {
            pp.load(new FileInputStream(realpath));
        }catch(Exception e){
            log.info("加载权限文件失败"+e.getMessage());
        }
    }

}
